from fastapi import APIRouter, status
from typing import Optional
from pydantic import BaseModel, Field
from orm.models import *
from common.error_codes import ErrorCode
import re

api_create_bug = APIRouter()


class BugInfo(BaseModel):
    bug_name: str = Field(..., title="缺陷名称", description="缺陷名称")
    bug_desc: Optional[str] = Field(None, title="缺陷描述", description="缺陷描述")
    bug_creator: str = Field(..., title="缺陷创建者", description="创建缺陷的员工")
    bug_assignee: str = Field(..., title="缺陷指派人", description="指派缺陷的员工")
    depart_id: int = Field(..., title="部门ID", description="部门ID")


@api_create_bug.post('/v1/create', status_code=status.HTTP_200_OK)
async def create_bug(bug: BugInfo):
    department_info = await Department.filter(id=bug.depart_id).first()
    employee_info = await department_info.employee.all()
    if not re.match(r"^[a-zA-Z\u4e00-\u9fa5\1-9]+$", bug.bug_name):
        return {
            "code":
            ErrorCode.FailCreateBugByBugName,
            "message":
            ErrorCode.get_error_message(ErrorCode.FailCreateBugByBugName)
        }
    if not Employee.filter(
            name=bug.bug_creator).first() or not Employee.filter(
                name=bug.bug_assignee).first():
        return {
            "code": ErrorCode.FailCreateBug,
            "message": ErrorCode.get_error_message(ErrorCode.FailCreateBug)
        }
    else:
        print('开始创建缺陷信息')
        department_info = await Department.get(id=bug.depart_id)  #查询到部门信息
        employee_queryset = await department_info.employee.all()
        employee_info = [emp for emp in employee_queryset]
        bug_info = await Bug_Info.create(bug_name=bug.bug_name,
                                         bug_desc=bug.bug_desc,
                                         bug_creator=bug.bug_creator,
                                         bug_assignee=bug.bug_assignee,
                                         depart_id=bug.depart_id)
        bug_data = {
            "bug_info": bug_info,
            "department_info": department_info,
            "employee_info": employee_info
        }
        return {"code": status.HTTP_200_OK, "message": "成功", "data": bug_data}
